<template>
<div>
  <a-table
    class="risk-vue-table risk-mini-size-table"
    :loading="pagination.loading"
    :columns="permsList.includes('matrix:ruleEngine')?columns:columns1"
    :data-source="dataList"
    :pagination="pagination"
    @change="pageChange"

    :scroll="{ x: true }"
  >
    <template slot="textOver" slot-scope="text">
      <span class="text-over" :title="text">{{ text }}</span>
    </template>


    <span slot="institutionStatus" slot-scope="text">
          {{ text | institutionStatus }}
    </span  >

    <template slot="associationInstitution" slot-scope="text, record">
      <span>
          <a type="link" @click="handleToDetail(record)">{{ text }}</a>
      </span>
    </template>
    <span slot="controlAttributeCode" slot-scope="text , record" >
        <span v-if="record.controlAttributeCode === 1" ><font color="#dc143c"> 法规要求</font></span>
        <span v-if="record.controlAttributeCode === 2">内控要求</span>
    </span>
    <template slot="switch" slot-scope="text, record">
      <span v-has-permi="['matrix:ruleEngine']" v-if='record.riskActivityNo'>
        <a-switch checked-children="是" un-checked-children="否" v-model="record.isRuleEngine"/>
      </span>
    </template>
    <template slot="ruleNumber" slot-scope="text, record">
      <span v-if='record.riskActivityNo' v-has-permi="['matrix:ruleEngine']" >
        <span>{{text}}</span>
        <a-button  type="primary" size="small" @click="handAction('ruleNumber', record, index)" shape="circle" icon="search" />
      </span>
    </template>
    <template slot="action" slot-scope="text, record">
      <a-button type="link" @click="handleEdit(record)" >编辑</a-button>

      <a-popconfirm
              title="请您确认是否删除该控制活动"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleDelete(record)"
              @cancel="cancel"
      >
        <a-button type="link" >删除</a-button>
      </a-popconfirm>

    </template>
  </a-table>
  <TableSelectModal selectType="radio"  width="85vw" :searchPlaceholder="'请输入规则编码或名称进行模糊查询'" ref="ruleSelect"
    @ok="selectRule" :isAllSelect='false' :listUrl='url.ruleList' :isEmptyShow='false'  :importColumns='selectColums' >
  </TableSelectModal>
  <add-activity ref="addActivity" @ok="handleOk" ></add-activity>
  </div>
</template>

<script>

// import { mergeCellKey} from './mergeCell'
import { institutionStatus } from '@/utils/filters';
import TableSelectModal from '@/components/tools/TableSelectModal';
import { postRiskAction ,getRiskAction } from '../../../api/manage';

import AddActivity from './modules/AddActivity.vue'
export default {
  name: 'MatrixDet',
  components: {
     TableSelectModal ,AddActivity
  },
  props: {
    companyCode: {
      type: String,
      require: true,
    } ,
    manageCode: {
      type: String,
      require: true,
    } ,
    businessModelId: {
      type: String,
      require: true,
    },
    total: {
      // eslint-disable-next-line no-undef
      type: Number ,
      require:false
    }
  },
  filters: {
    institutionStatus
  },
  data() {
    return {
      pagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '30', '50' , '100'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条';
        },
        total: 0,
        loading: false,
      },
      columns:[
        {title: 'L1',dataIndex: 'level1Name',align: 'center',width: 100,},
        {title: 'L2',dataIndex: 'level2Name',align: 'center',width: 100,},
        {title: '风险点编号',dataIndex: 'riskNo',align: 'center', width: 180,
          customRender: (value, row, index) => {
            const obj = {
              children: this.$createElement('div',{ class: 'col-tit' },
                [
                  this.$createElement('p',{
                    domProps: {
                      innerHTML: value
                    }
                  }),
                  this.$createElement('div', [
                    this.$createElement('span', {
                      domProps: {
                        innerHTML: '问题整改'
                      },
                      class: 'btn-line-right',
                      on: {
                        click: () => {
                          this.onHandClick(row, index, '整改')
                        }
                      },
                    }),
                    this.$createElement('span',{
                      domProps: {
                        innerHTML: '风控评价'
                      },
                      class: 'btn-line-right',
                      on: {
                        click: () => {
                          this.onHandClick(row, index, '评价')
                        }
                      },
                    }),
                  ]),
                ],
              ),
              attrs: {},
            };
            // obj.attrs.rowSpan = mergeCellKey(row.riskNo, this.dataList, 'riskNo');
            return obj;
          }
        },
        {
          title: '风险因素',
          dataIndex: 'riskFactor',
          align: 'center',
          width: 130,scopedSlots: { customRender: 'textOver' },
        },
        {title: '风险事件',dataIndex: 'riskEvent',align: 'center',width: 130,scopedSlots: { customRender: 'textOver' },
        },
        // {title: '后果（损失）',dataIndex: 'riskLoss',align: 'center',width: 130,scopedSlots: { customRender: 'textOver' },
        // },
        // {title: '风险类型',dataIndex: 'riskTypeName',align: 'center',width:100,},
        // {title: '风险评分',width: 100,dataIndex: 'assessImplement.riskScore',align: 'center',},

        {title: '控制活动编号',width: 150,dataIndex: 'riskActivityNo',align: 'center'},
        {
          title: '控制活动',
          width: 120,
          dataIndex: 'riskActivity',
          align: 'center',
          scopedSlots: { customRender: 'textOver' }
        },
      {
          title:'控制属性' ,
          align:"center",
          width:90 ,
          dataIndex: 'controlAttributeCode' ,
          scopedSlots: { customRender: 'controlAttributeCode' },
      },
        {title: '检测点',width: 100,dataIndex: 'monitorPoint',align: 'center',},
        {title: '控制类型',width: 100,dataIndex: 'controlType',align: 'center',},
        {title: '是否线上控制',width: 120,dataIndex: 'isOnline',align: 'center',},
        {title: '控制系统',width: 100,dataIndex: 'controlSystem',align: 'center',},
        {title: '审批流名称',width: 110,dataIndex: 'approvalName',align: 'center',},
        {title: '关联制度',width: 100,dataIndex: 'associationInstitution',align: 'center',scopedSlots: { customRender: 'associationInstitution' }},
        {
          title: '制度状态',
          dataIndex: 'institutionStatus',
          scopedSlots: { customRender: 'institutionStatus' },
          align: 'center',
          width: 80
        },
        {
          title:'是否引入规则引擎' ,
          align:"center",
          width:90 ,
          dataIndex: 'isRuleEngine' ,
          scopedSlots: { customRender: 'switch' },
        },
        {
          title:'规则编号' ,
          align:"center",
          width:120 ,
          dataIndex: 'ruleNumber' ,
          scopedSlots: { customRender: 'ruleNumber' },
        },
        {
          title:'操作' ,
          align:"center",
          width:120 ,
          dataIndex: 'action' ,
          scopedSlots: { customRender: 'action' },
        }
      ],
      columns1:[
        {title: 'L1',dataIndex: 'level1Name',align: 'center',width: 100,},
        {title: 'L2',dataIndex: 'level2Name',align: 'center',width: 100,},
        {title: '风险点编号',dataIndex: 'riskNo',align: 'center', width: 180,
          customRender: (value, row, index) => {
            const obj = {
              children: this.$createElement('div',{ class: 'col-tit' },
                      [
                        this.$createElement('p',{
                          domProps: {
                            innerHTML: value
                          }
                        }),
                        this.$createElement('div', [
                          this.$createElement('span', {
                            domProps: {
                              innerHTML: '问题整改'
                            },
                            class: 'btn-line-right',
                            on: {
                              click: () => {
                                this.onHandClick(row, index, '整改')
                              }
                            },
                          }),
                          this.$createElement('span',{
                            domProps: {
                              innerHTML: '风控评价'
                            },
                            class: 'btn-line-right',
                            on: {
                              click: () => {
                                this.onHandClick(row, index, '评价')
                              }
                            },
                          }),
                        ]),
                      ],
              ),
              attrs: {},
            };
            // obj.attrs.rowSpan = mergeCellKey(row.riskNo, this.dataList, 'riskNo');
            return obj;
          }
        },
        {
          title: '风险因素',
          dataIndex: 'riskFactor',
          align: 'center',
          width: 130,scopedSlots: { customRender: 'textOver' },
        },
        {title: '风险事件',dataIndex: 'riskEvent',align: 'center',width: 130,scopedSlots: { customRender: 'textOver' },
        },
        // {title: '后果（损失）',dataIndex: 'riskLoss',align: 'center',width: 130,scopedSlots: { customRender: 'textOver' },
        // },
        // {title: '风险类型',dataIndex: 'riskTypeName',align: 'center',width:100,},
        // {title: '风险评分',width: 100,dataIndex: 'assessImplement.riskScore',align: 'center',},

        {title: '控制活动编号',width: 150,dataIndex: 'riskActivityNo',align: 'center'},
        {
          title: '控制活动',
          width: 120,
          dataIndex: 'riskActivity',
          align: 'center',
          scopedSlots: { customRender: 'textOver' }
        },
        {
          title:'控制属性' ,
          align:"center",
          width:90 ,
          dataIndex: 'controlAttributeCode' ,
          scopedSlots: { customRender: 'controlAttributeCode' },
        },
        {title: '检测点',width: 100,dataIndex: 'monitorPoint',align: 'center',},
        {title: '控制类型',width: 100,dataIndex: 'controlType',align: 'center',},
        {title: '是否线上控制',width: 120,dataIndex: 'isOnline',align: 'center',},
        {title: '控制系统',width: 100,dataIndex: 'controlSystem',align: 'center',},
        {title: '审批流名称',width: 110,dataIndex: 'approvalName',align: 'center',},
        {title: '关联制度',width: 100,dataIndex: 'associationInstitution',align: 'center',scopedSlots: { customRender: 'associationInstitution' }},
        {
          title: '制度状态',
          dataIndex: 'institutionStatus',
          scopedSlots: { customRender: 'institutionStatus' },
          align: 'center',
          width: 80
        },
      ],
      dataList: [],
      permsList:[],
      mergeList: [],
      selectColums:[
        {title: '规则编号',dataIndex: 'code',align: 'center',},
        {title: '规则名称',dataIndex: 'title',align: 'center'},
        {title: '业务模块',dataIndex: 'deptName',align: 'center',}
      ],
      currentRow:{},
      url:{
        ruleList:'/incExceptionOrder/ruleList',
        saveRule:'/incExceptionOrder/saveRule' ,
        getActivityById:'/incActivity/getActivityById',
        delete:'/incActivity/delete',
        getIncPermission:'/inc/getIncPermissions'
      }
    };
  },
  mounted()
  {
    this.getIncPermission();
  },
  methods: {
    pageChange(page) {
      this.pagination.current = page.current;
      this.pagination.pageSize = page.pageSize;
      this.$emit('pageChange' , this.pagination )
      // this.getInitData();
    },
    handleOk(){
      this.$emit('ok' )
    },
    handAction(type, item){
      if(type =="ruleNumber"){
        this.currentRow = item;
        this.$refs.ruleSelect.open()
        // this.$refs.riskSelect.queryParam={  status: 3,parentId: ''}
      }
    },
    getIncPermission(){
      getRiskAction(this.url.getIncPermission).then(res => {
        if (res.code == 0){
          debugger
          let result = res.data
          this.permsList = result.perms
        }
      })
    },

    setListData(data){
      this.dataList = data;
        this.$set(this.pagination , 'total' , this.total)
      // this.$forceUpdate();
    },
    onHandClick(val, index, text) {
      debugger
      console.log('法人公司' , this.companyCode)
      let routeUrl;
      if ('整改' == text) {
        const routeUrl = this.$router.resolve({
          path: '/internal/matrix/lssue',
          query: {
            id: val.riskId,
            companyCode: this.companyCode,
            manageCode: this.manageCode,
            businessModelId: this.businessModelId
          }
        });
        window.open(routeUrl.href, '_blank');
      }
      if ('评价' == text) {
        routeUrl = this.$router.resolve({
          path: '/internal/matrix/assess',
          query:
                  {
                    id: val.riskId,
                    companyCode: this.companyCode,
                    manageCode: this.manageCode,
                    businessModelId: this.businessModelId
                  }
        });
        window.open(routeUrl.href, '_blank');
      }
    },
    handleToDetail(item){
      debugger
      let routeUrl = this.$router.resolve({
        path: '/institution/detail?institutionId=' + item.institutionId + '&showRange=0'
      });
      window.open(routeUrl.href, '_blank');
    },
    handleEdit(record){
      console.log('数据记录' , record)
      getRiskAction(this.url.getActivityById , {id : record.id}).then(res => {
        if (res.code == 0){
          let result = res.data
          this.$set(result , 'institutionStatus' , record.institutionStatus)
          this.$refs.addActivity.setForm(result)

          setTimeout(() => {
            this.$refs.addActivity.showModal()

          }, 100);
        }
      })
    },
    cancel(e) {},
    //删除控制活动
    handleDelete(record){
      getRiskAction(this.url.delete , {id : record.id}).then(res => {
        if (res.code == 0){
          this.$message.success(res.msg)
          //刷新数据
          this.$emit('ok' )
        }
      })
    },
    selectRule(res){
       //选择风险点
      console.log('选择规则：' + res )
      if(res.length>0){
        this.$set(this.currentRow,'ruleNumber',res[0].code);
        this.$set(this.currentRow,'ruleName',res[0].title);
        const param = {"riskActivityNo":this.currentRow.riskActivityNo,'ruleNumber':this.currentRow.ruleNumber,'ruleName':this.currentRow.ruleName,
        "ruleModule":res[0].deptName}
        postRiskAction(this.url.saveRule , param).then( res => {
          if (res.code !== 0){
            this.$message.error(res.msg)
          }
        });
      }
      this.$refs.ruleSelect.handleCancel()
    },
  }
};
</script>
<style lang="scss" scoped>
::v-deep .ant-table-thead > tr:not(:last-child) > th {padding: 5px 16px;font-weight: bold;
  &:nth-child(1){background-color: #E1E8F6;color: #4183D9;}
  &:nth-child(2){background-color: #D4EEE4;color: #407E67}
}
.col-tit{
  p{margin-bottom: 0}
  >div.btn{color: #5690dc;
    border-right: 1px solid #e6e6e6;
    &:last-of-type{border-right: none;}
  }
  .btn-line-right{position: relative;color: #5690DC;font-size: 12px;font-weight: bold;padding: 2px 0;cursor: pointer;margin-top: 5px;display: inline-block;
    &:after{position: absolute;display: inline-block;content: '';width: 1px;height: 80%;bottom: 10%;right: 10px;background-color: #c9d8e7;}
    &:first-of-type{padding-right: 20px}
    &:last-of-type{
      &:after{display: none;}
    }
    &:hover{color: #539af8}
  }
}

</style>
